import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'
Vue.use(VueRouter)
// 封装一个判断当前模块是否有权限的方法
function hasUrl (url, next) {
//  判断当前地址是否在 menus数组中， 如果在就放行 ,不在就拦截
  const result = store.getters.getUser.menus_url.some(item => url === item)
  if (result) {
    next()
  } else {
    next('/home')
  }
}
const login = () => import('../pages/login/login.vue')
const home = () => import('../pages/home/home.vue')
//  菜单管理
const menu = () => import('../pages/menu/manage/manage.vue')
//  角色 管理
const role = () => import('../pages/role/manage/index.vue')
//  管理员管理
const conservator = () => import('../pages/conservator/index.vue')
const classify = () => import('../pages/goods/classify/classify.vue')
const sku = () => import('../pages/goods/sku/sku.vue')
const cmmg = () => import('../pages/goods/cmmg/cmmg.vue')
const banner = () => import('../pages/goods/banner/banner.vue')
const seckill = () => import('../pages/goods/seckill/seckill.vue')
const mrm = () => import('../pages/goods/member/member.vue')

export const indexRoute = [
  {
    path: '/role',
    component: role,

    meta: {
      title: '角色管理'
    },
    // 路由独享守卫
    beforeEnter (to, from, next) {
      hasUrl('/role', next)
    }
  },
  {

    path: '/conservator',
    meta: {
      title: '菜单管理'
    },
    component: conservator
  },
  {

    path: '/classify',
    meta: {
      title: '商品分类'
    },
    component: classify
  },
  {

    path: '/sku',
    meta: {
      title: '商品规格'
    },
    component: sku
  },
  {
    path: '/cmmg',
    meta: {
      title: '商品管理'
    },
    component: cmmg
  },
  {

    path: '/banner',
    meta: {
      title: '轮播图管理'
    },
    component: banner
  },
  {

    path: '/seckill',
    meta: {
      title: '秒杀管理'
    },
    component: seckill
  },
  {

    path: '/mrm',
    meta: {
      title: '会员管理'
    },
    component: mrm
  }

]
const routes = [
  {
    path: '/home',
    component: home,
    children: [
      ...indexRoute,

      {
        path: '/menu',
        component: menu

      }
    ]
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '*',
    redirect: '/home'
  }

]
// 分装全局登录事件

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
    return
  }
  // 判断用户是否登录
  if (store.getters.getUser) {
    next()
    return false
  }
  // 如果未登录 就强制跳转到 登录
  next('/login')
})
export default router
